import { Context } from 'egg';

export default () =>
  async function auth(ctx: Context, next: () => Promise<void>) {
    if (ctx.app.config.ignoreAuth.some((s: string) => ctx.request.url.startsWith(s))) {
      return await next();
    }
    const token = ctx.headers.authorization;

    let decode: any = null;
    try {
      decode = ctx.app.jwt.verify(token!, ctx.app.config.jwt.secret) as any;
      if (decode.exp <= Date.now() / 1000) {
        ctx.status = 401;
        ctx.body = {
          code: -1,
          message: '登录状态已过期',
        };
      } else {
        ctx.user = {
          id: decode.id,
          username: decode.username,
        };
      }
    } catch (err) {
      ctx.status = 401;
      ctx.body = {
        code: -1,
        message: '登录状态无效',
      };
    }

    await next();
  };
